package tw.com.diary.core;

import java.util.ArrayList;
import java.util.List;

import tw.com.diary.ae.com.DirayBussinessException;
import tw.com.diary.api.domain.UnWriteListDTO;
import tw.com.diary.api.service.UnWriteListService;
import tw.com.diary.dao.X0001BackDAO;
import tw.com.diary.dao.X0001DAO;
import tw.com.diary.db.domain.X0001;
import tw.com.diary.db.domain.X0001Back;
import tw.com.diary.db.util.DBHelp;
import tw.com.diary.db.util.DirDateBean;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

/**
 * 未填寫服務
 * 
 * @author Andy
 * 
 */
public class UnWriteListServiceImpl implements UnWriteListService {

	private X0001 clone(X0001Back back) {
		final X0001 x001 = new X0001();
		x001.setContent(back.getContent());
		x001.setUuid(back.getUuid());
		x001.setWeather(back.getWeather());
		x001.setYyyymmdd(back.getYyyymmdd());
		return x001;

	}

	@Override
	public void queryRecord(UnWriteListDTO dto, Context context) throws DirayBussinessException {

		// 取得本月份列出時間已過與今天尚未填寫日記清單，
		// 先查詢當月已經寫日記清單，比較剩下的表示尚未填寫日記清單，
		//

		DBHelp help = DBHelp.intance(context);

		SQLiteDatabase conn = help.getWritableDatabase();
		X0001DAO dao = new X0001DAO(conn);
		X0001BackDAO x0001BackDAO = new X0001BackDAO(conn);

		final DirDateBean bean = new DirDateBean();

		List<X0001> x001s = dao.selectListYearMon(bean.getYyyymm());

		List<X0001> tmp = new ArrayList<X0001>();

		
		//==取得封裝資料==表示已經寫過日記，只是存封起來
		List<X0001Back> tmpBack = x0001BackDAO.selectListYearMon(bean.getYyyymm());

		for (X0001Back back : tmpBack) {
			tmp.add(this.clone(back));
		}
		tmpBack = null;

		for (int i = 1; i <= bean.getDay(); i++) {
			final X0001 x0001 = new X0001();
			x0001.setYyyymmdd(String.format(bean.getYyyymm() + "%02d", i));
			tmp.add(x0001);

		}
		final List<X0001> yearModayDay = new ArrayList<X0001>();

		for (X0001 x001 : tmp) {
			int index = x001s.indexOf(x001);
			if (index == -1) {
				yearModayDay.add(x001);
			}
		}
		conn.close();
		dto.getUnWriteList().clear();
		dto.getUnWriteList().addAll(yearModayDay);// 未填寫清單

	}
}
